<template>
  <div class="dimission-container">
    <el-card class="dimission-header">
      <template #header>
        <div class="card-header">
          <span>离职档案</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增离职
          </el-button>
        </div>
      </template>

      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="员工姓名">
          <el-input v-model="queryForm.employee_name" placeholder="请输入员工姓名" clearable />
        </el-form-item>
        <el-form-item label="离职类型">
          <el-select v-model="queryForm.dimission_type" placeholder="请选择离职类型" clearable>
            <el-option label="主动离职" value="主动离职" />
            <el-option label="被动离职" value="被动离职" />
            <el-option label="合同到期" value="合同到期" />
            <el-option label="协商解除" value="协商解除" />
          </el-select>
        </el-form-item>
        <el-form-item label="离职日期">
          <el-date-picker
            v-model="queryForm.dimission_date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="dimission-content">
      <el-table :data="tableData" style="width: 100%" height="calc(100vh - 330px)">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="employee_name" label="员工姓名" />
        <el-table-column prop="department_name" label="部门" />
        <el-table-column prop="position_name" label="职位" />
        <el-table-column prop="entry_date" label="入职日期" />
        <el-table-column prop="dimission_date" label="离职日期" />
        <el-table-column prop="dimission_type" label="离职类型" />
        <el-table-column prop="reason" label="离职原因" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="员工" prop="employee_id">
          <el-select v-model="formData.employee_id" placeholder="请选择员工" filterable>
            <el-option v-for="emp in employees" :key="emp.id" :label="emp.name" :value="emp.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="离职类型" prop="dimission_type">
          <el-select v-model="formData.dimission_type" placeholder="请选择离职类型">
            <el-option label="主动离职" value="主动离职" />
            <el-option label="被动离职" value="被动离职" />
            <el-option label="合同到期" value="合同到期" />
            <el-option label="协商解除" value="协商解除" />
          </el-select>
        </el-form-item>
        <el-form-item label="离职日期" prop="dimission_date">
          <el-date-picker
            v-model="formData.dimission_date"
            type="date"
            placeholder="选择离职日期"
          />
        </el-form-item>
        <el-form-item label="最后工作日期" prop="last_work_date">
          <el-date-picker
            v-model="formData.last_work_date"
            type="date"
            placeholder="选择最后工作日期"
          />
        </el-form-item>
        <el-form-item label="离职原因" prop="reason">
          <el-input
            v-model="formData.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入离职原因"
          />
        </el-form-item>
        <el-form-item label="交接事项" prop="handover">
          <el-input
            v-model="formData.handover"
            type="textarea"
            :rows="3"
            placeholder="请输入工作交接事项"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Search, Refresh } from '@element-plus/icons-vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { dimissionApi } from '@/api/user/dimission'
  import { userApi } from '@/api/user'

  interface Dimission {
    id: number
    employee_id: number
    employee_name: string
    department_name: string
    position_name: string
    entry_date: string
    dimission_date: string
    last_work_date: string
    dimission_type: string
    reason: string
    handover: string
    remark: string
  }

  interface Employee {
    id: number
    name: string
    department_name?: string
    position_name?: string
    entry_date?: string
    department?: string
    position?: string
  }

  const queryForm = reactive({
    employee_name: '',
    dimission_type: '',
    dimission_date_range: [] as string[],
  })

  const tableData = ref<Dimission[]>([])
  const employees = ref<Employee[]>([])

  const pagination = reactive({
    page: 1,
    limit: 10,
    total: 0,
  })

  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const submitLoading = ref(false)
  const formRef = ref<FormInstance>()

  const formData = reactive({
    id: undefined as number | undefined,
    employee_id: undefined as number | undefined,
    dimission_type: '',
    dimission_date: '',
    last_work_date: '',
    reason: '',
    handover: '',
    remark: '',
  })

  const rules: FormRules = {
    employee_id: [{ required: true, message: '请选择员工', trigger: 'change' }],
    dimission_type: [{ required: true, message: '请选择离职类型', trigger: 'change' }],
    dimission_date: [{ required: true, message: '请选择离职日期', trigger: 'change' }],
    last_work_date: [{ required: true, message: '请选择最后工作日期', trigger: 'change' }],
    reason: [{ required: true, message: '请输入离职原因', trigger: 'blur' }],
  }

  const loadDimissionList = async () => {
    try {
      const params: any = {
        ...queryForm,
        page: pagination.page,
        limit: pagination.limit,
      }

      if (queryForm.dimission_date_range && queryForm.dimission_date_range.length === 2) {
        params.start_date = queryForm.dimission_date_range[0]
        params.end_date = queryForm.dimission_date_range[1]
      }

      const res = await dimissionApi.getList(params)
      if (res.code === 0) {
        tableData.value = res.data.list
        pagination.total = res.count || 0
      }
    } catch (error) {
      console.error('加载离职列表失败:', error)
    }
  }

  const loadEmployees = async () => {
    try {
      const res = await userApi.getUserList({ page: 1, limit: 1000 })
      if (res.code === 0) {
        employees.value = res.data.list.map((user: any) => ({
          id: user.id,
          name: user.name || user.username,
          department: user.department,
          department_name: user.department_name || user.department,
          position_name: user.position_name || user.position,
          entry_date: user.entry_date || user.created_at,
        }))
      }
    } catch (error) {
      console.error('加载员工列表失败:', error)
    }
  }

  const handleSearch = () => {
    pagination.page = 1
    loadDimissionList()
  }

  const handleReset = () => {
    queryForm.employee_name = ''
    queryForm.dimission_type = ''
    queryForm.dimission_date_range = []
    handleSearch()
  }

  const handleAdd = () => {
    dialogTitle.value = '新增离职'
    dialogVisible.value = true
  }

  const handleEdit = (row: Dimission) => {
    dialogTitle.value = '编辑离职'
    Object.assign(formData, {
      id: row.id,
      employee_id: row.employee_id,
      dimission_type: row.dimission_type,
      dimission_date: row.dimission_date,
      last_work_date: row.last_work_date,
      reason: row.reason,
      handover: row.handover,
      remark: row.remark,
    })
    dialogVisible.value = true
  }

  const handleView = (row: Dimission) => {
    ElMessage.info(`查看 ${row.employee_name} 的离职详情`)
  }

  const handleDelete = async (row: Dimission) => {
    try {
      await ElMessageBox.confirm('确定要删除该离职记录吗？', '提示', {
        type: 'warning',
      })
      const res = await dimissionApi.delete(row.id)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        loadDimissionList()
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除离职记录失败:', error)
      }
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitLoading.value = true

      const api = formData.id ? dimissionApi.edit : dimissionApi.add
      const res = await api(formData)

      if (res.code === 0) {
        ElMessage.success(formData.id ? '编辑成功' : '新增成功')
        dialogVisible.value = false
        loadDimissionList()
      }
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  const handleDialogClose = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.assign(formData, {
      id: undefined,
      employee_id: undefined,
      dimission_type: '',
      dimission_date: '',
      last_work_date: '',
      reason: '',
      handover: '',
      remark: '',
    })
  }

  const handleSizeChange = (val: number) => {
    pagination.limit = val
    loadDimissionList()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    loadDimissionList()
  }

  onMounted(() => {
    loadDimissionList()
    loadEmployees()
  })
</script>

<style scoped lang="scss">
  .dimission-container {
    padding: 20px;
  }

  .dimission-header {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-top: 20px;
  }

  .dimission-content {
    .el-pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }
</style>
